package com.yunfei.commonbase.base64;

import com.yunfei.commonbase.exception.DataException;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;

public class Base64Utils {

    /**
     * 生产base64密文
     * @param decoder
     * @return
     */
    public static String getBase64encoderString(String decoder) throws DataException {
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0;i<8;i++){
            if(i==2){
                stringBuilder.append(decoder);
            }else{
                stringBuilder.append(UUID.randomUUID().toString().replaceAll("-",""));
            }
        }
        String base64encoderString = "";
        try {
            base64encoderString = Base64.getEncoder().encodeToString(stringBuilder.toString().getBytes("utf-8"));
        }catch (Exception e){
           throw new DataException("加密失败");
        }
        return base64encoderString;
    }
    /**
     * 解密base64密文
     */

    public static String getBase64decoderString (String encoder) throws Exception {
        byte[] base64decodedBytes = Base64.getDecoder().decode(encoder);
        String decoder = "";
        try {
            decoder = new String(base64decodedBytes, "utf-8");
            decoder = decoder.substring(64,decoder.length()-160);
        }catch ( Exception e){
            throw new Exception("解密失败");
        }
        return decoder;
    }

    public static void main(String[] args) throws Exception {
        String yunfei = getBase64encoderString("yxsFL#5VZ%Rl1BjYBB");
        System.out.println(yunfei);
        String msg ="N2I3YzkxMDY0MWMyNGFiYTgwOTA4YmIwMWFjNWUxMTM1NGRjYjczZjM3NTg0MGNhODljZjUxYzBhNWYxZTg4MHl4c0ZMIzVWWiVSbDFCallCQjMwZTJmMGM5YzRiNjQxYTg4OGUwZTg1NTI3OTkxYmVlMzA1NGI3MmIyNTAwNDc0MjkwN2UxM2FmNmJiODI1MTk3YTFlNmUxY2JlNzE0MjI2OTNhZTI5ZGYwYjM3ODY2NTM4Y2Q0Nzg1OGU4YjRjNjE5ZDAxNjRhZmY5ODExODliNzg3Y2JiNmQwZjQxNDU2NWI1NDMzZTZiMWU4MjFiMWU=";
        String base64decoderString = getBase64decoderString(msg);
        System.out.println(base64decoderString);
    }
}
